package com.fh.controller.system.thesis;

import com.fh.controller.base.BaseController;
import com.fh.entity.Page;
import com.fh.entity.system.Student;
import com.fh.entity.system.User;
import com.fh.service.system.dictionaries.DictionariesService;
import com.fh.service.system.role.RoleService;
import com.fh.service.system.student.StudentService;
import com.fh.service.system.supervisor.SupervisorService;
import com.fh.service.system.title.TitleService;
import com.fh.service.system.topictime.TopicTimeService;
import com.fh.service.system.user.UserService;
import com.fh.util.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.UndeclaredThrowableException;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

/**
 * 类名称：ThesisController
 * 创建人：FH
 * 创建时间：2015-07-30
 */
@Controller
@RequestMapping(value = "/thesis")
public class ThesisController extends BaseController {

	String menuUrl = "title/list.do"; //菜单地址(权限用)

	@Resource(name = "titleService")
	private TitleService titleService;

	@Resource(name = "roleService")
	private RoleService roleService;


	@Resource(name = "dictionariesService")
	private DictionariesService dictionariesService;

	@Resource(name = "topictimeService")
	private TopicTimeService topictimeService;


	@Resource(name = "supervisorService")
	private SupervisorService supervisorService;

	@Resource(name = "studentService")
	private StudentService studentService;

	@Resource(name = "userService")
	private UserService userService;

	@RequestMapping(value = "/thesistitle_list")
	public ModelAndView thesistitle_list(Page page) throws Exception {
		logBefore(logger, "列表Title");
		//if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();

		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();

		User user = (User) session.getAttribute(Const.SESSION_USER);
		pd.put("USERNAME", user.getUSERNAME());
		pd = studentService.findByUsername(pd);


		//查出是专科还是本科
		String PROFESSION_ID = pd.getString("PROFESSION_ID");
		String xianxuan;
		PageData pdp = new PageData();
		pdp.put("BIANMA", PROFESSION_ID);
		if (dictionariesService.findByBM(pdp).getString("ATTRIBUTE").equals("本科")) {
			xianxuan = "本%";
		} else {
			xianxuan = "专%";
		}
		pd.put("XIANXUAN", xianxuan);


		try {
			List<PageData> varList = titleService.findByDepart(pd);    //列出Title列表


			mv.setViewName("system/thesis/thesis_list");
			mv.addObject("varList", varList);
			mv.addObject("pd", pd);

			Map<String, String> hc = this.getHC();
			hc.put("cha", "1");
			mv.addObject(Const.SESSION_QX, hc);    //按钮权限
		} catch (UndeclaredThrowableException e) {
			e.getUndeclaredThrowable();
		}
		return mv;
	}


	@RequestMapping(value = "/thesistitle_detail")
	public ModelAndView thesistitle_detail() throws Exception {
		logBefore(logger, "thesistitle_detail");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			pd = titleService.findById(pd);    //根据ID读取
			mv.setViewName("system/thesis/thesistitle_detail");

			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}


//synchronized

	/*
	* 1.读取选题时间
	* 	判断选题时间
	* 2.是否选题
	* 3.是否允许选题（待补充）
	* 4.锁定
	* 	a.选题或老师人数是否满，满就解锁退出
	* 	b.选题，解锁
	*
	*	pd.put("LAST_LOGIN",DateUtil.getTime().toString());
	*	SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date1=formate.parse("2012-08-02 12:23:22");
	*	@pageData{QQ=21354683213,
	 			DEPARTMENT_NAME=通信工程学院,
	 			IS_AFFIRM=1,
	 			TITLE_NAME=马克思,
	 			XIANXUAN=本,
	 			SUPERVISOR=人发的,
	 			EMAIL=1238523542,
	 			YAOQIU=100000000字,
	 			LAIYUAN=社会,
	 			CURRENTNUMBER=21,
	 			TITLE_ID=fe9d20a5621a41b2a21a8a63a627181b,
	 			DEPARTMENT_XI=YX_02,
		 		TELPHONE=1234566,
				MAXNUMBER=20,
		 		FANGXIANG=哲学}

	* */

	@RequestMapping(value = "/choice")
	@ResponseBody
	public Object choice() throws Exception {
		logBefore(logger, "thesis/choice");
		PageData pageData = this.getPageData();
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User) session.getAttribute(Const.SESSION_USER);
		Map<String, String> map = new HashMap<String, String>();


		//1、时间判断
		SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date1=formate.parse("2012-08-02 12:23:22");
		Date currentTime=formate.parse(DateUtil.getTime());	//当前时间
		String PROFESSION_ID = user.getPROFESSION_ID();
		System.out.println("PROFESSION_ID" + PROFESSION_ID);
		PageData pd = new PageData();
		pd.put("PROFESSION_ID", PROFESSION_ID);
		pd.put("DEPARTMENT_ID", user.getDEPARTMENT_ID());
		pd = topictimeService.findByYXandZY(pd);
		System.out.println("pd" + pd);
		if (pd == null) {
			map.put("result", "没有找到该专业的选题时间表");
			return AppUtil.returnObject(new PageData(), map);
		}
		Date startTime=formate.parse(pd.getString("TOPICSTARTTIME"));
		Date endTime = formate.parse(pd.getString("TOPICENDTIME"));
		if (currentTime.before(startTime)) {
			map.put("result", "选题时间未到！选题时间："+pd.getString("TOPICSTARTTIME")+"-"+pd.getString("TOPICENDTIME"));
			return AppUtil.returnObject(new PageData(), map);
		}
		if (currentTime.after(endTime)) {
			map.put("result", "选题时间已超过！选题时间："+pd.getString("TOPICSTARTTIME")+"-"+pd.getString("TOPICENDTIME"));
			return AppUtil.returnObject(new PageData(), map);
		}

		//2、判断是否已经选题
		pd.put("USER_ID", user.getUSER_ID());
		if (titleService.findByIdInResultTab(pd)!=null) {
			map.put("result", "你已经选题了，不能重复选题！");
			return AppUtil.returnObject(new PageData(), map);
		}


		{
			//3、判断题目人数上限
			//pageData
			pageData = titleService.findById(pageData);
			int MAXNUMBER = Integer.parseInt(pageData.getString("MAXNUMBER"));
			int CURRENTNUMBER = Integer.parseInt(pageData.getString("CURRENTNUMBER"));
			if (MAXNUMBER <= CURRENTNUMBER) {
				map.put("result", "此题目已达到选题人数上限，不能选此题目！");
				return AppUtil.returnObject(new PageData(), map);
			}

			//4、判断导师人数上限
			String SUPERVISOR = pageData.getString("SUPERVISOR");
			String ATTRIBUTE;//本科还是专科
			pageData.put("BIANMA", PROFESSION_ID);
			ATTRIBUTE = dictionariesService.findByBM(pageData).getString("ATTRIBUTE");
			if ("专科".equals(ATTRIBUTE)) {
				ATTRIBUTE = "专%";
			}else ATTRIBUTE = "本%";
			pageData.put("ATTRIBUTE", ATTRIBUTE);
			PageData pdp = supervisorService.findByAttr(pageData);
			System.out.println(pdp);
			int S_MAXNUMBER = Integer.parseInt(pdp.getString("S_MAXNUMBER"));
			int S_CURRENTNUMBER = Integer.parseInt(pdp.getString("S_CURRENTNUMBER"));
			if (S_MAXNUMBER <= S_CURRENTNUMBER) {
				map.put("result", "当前导师所带学生人数已满");
				return AppUtil.returnObject(new PageData(), map);
			}

			//5、选题操作，操作题目、导师、选题结果表
			pageData.put("CURRENTNUMBER", ++CURRENTNUMBER + "");
			titleService.edit(pageData);
			pdp.put("S_CURRENTNUMBER", ++S_CURRENTNUMBER + "");
			supervisorService.edit(pdp);

			String CHOICERESULT_ID = get32UUID();
			String STUDENT_ID = user.getUSER_ID();
			String TITLE_ID = pageData.getString("TITLE_ID");
			String SUPERVISOR_ID = pdp.getString("SUPERVISOR_ID");
			String CHOICE_TIME = DateUtil.getTime();		//当前时间 YYYY-MM-DD HH:mm:ss

			pageData = new PageData();
			pageData.put("CHOICERESULT_ID", CHOICERESULT_ID);
			pageData.put("STUDENT_ID", STUDENT_ID);
			pageData.put("TITLE_ID", TITLE_ID);
			pageData.put("CHOICE_TIME", CHOICE_TIME);
			pageData.put("SUPERVISOR_ID", SUPERVISOR_ID);
			titleService.saveChoiceResult(pageData);
			map.put("result", "success");
			return AppUtil.returnObject(new PageData(), map);
		}
	}




	@RequestMapping(value = "/mythesis")
	public ModelAndView myThesis() throws Exception {
		logBefore(logger, "mythesis");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try {
			Subject currentUser = SecurityUtils.getSubject();
			Session session = currentUser.getSession();
			User user = (User) session.getAttribute(Const.SESSION_USER);
			pd.put("STUDENT_ID", user.getUSER_ID());
			pd = titleService.findTitleByStuId(pd);    //根据student_ID读取title信息
			System.out.println(""+pd);
			mv.setViewName("system/thesis/mythesis");

			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}



	/* ===============================权限================================== */
	public Map<String, String> getHC() {
		Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
		Session session = currentUser.getSession();
		return (Map<String, String>) session.getAttribute(Const.SESSION_QX);
	}
	/* ===============================权限================================== */

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format, true));
	}
}
